#!/usr/bin/env python3
# 统计目录中所有代码文件的代码行数
import os
import sys


def count_lines_in_dir(dirpath):
    count = 0
    language = sys.argv[2]
    if language == 'python':
        exts = ['.py']
    elif language == 'java':
        exts = ['.java']
    elif language == 'c':
        exts = ['.h', '.c']
    else:
        print(f'Unsupported language: {language}')
        sys.exit(1)
    for dirpath, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            extension = os.path.splitext(filename)[1]
            if extension in exts:
                filepath = os.path.join(dirpath, filename)
                with open(filepath, 'r') as f:
                    for line in f:
                        if line.strip():
                            count += 1
    return count


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print(f'Usage: {sys.argv[0]} DIRECTORY FILE-TYPE')
    else:
        dirpath = sys.argv[1]
        if not os.path.isdir(dirpath):
            print(f'{dirpath} is not a directory')
        else:
            subdirs = [subdir for subdir in os.listdir(dirpath)
                       if os.path.isdir(os.path.join(dirpath, subdir))
                          and not subdir.startswith('.')]
            results = []
            for subdir in subdirs:
                count = count_lines_in_dir(os.path.join(dirpath, subdir))
                if count > 0:
                    results.append((subdir, count))
            results.sort(key=lambda x: x[1], reverse=True)
            for subdir, count in results:
                print(f'{count:5d} lines in directory {subdir}')
